package com.smartum.mpr.client.event;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartum.mpr.client.Authorization;
import com.smartum.mpr.client.presenter.LoginPresenter;
import com.smartum.mpr.client.services.UserService;
import com.smartum.mpr.client.services.UserServiceAsync;
import com.smartum.mpr.client.view.MaskPanel;
import com.smartum.mpr.shared.User;

/**
 * Calls when user click on login button.
 * <p/>
 * First it verifies the form and if it passed send request to the {@link UserService}. Gets response and navigate to the
 * admin console on successful result, and shows exception otherwise.
 */
public class LoginButtonHandler implements ClickHandler {

    private LoginPresenter presenter;
    private LoginPresenter.Display display;

    public LoginButtonHandler(LoginPresenter presenter) {
        this.presenter = presenter;
        this.display = presenter.getDisplay();
    }

    public void onClick(ClickEvent event) {
        doAdminConsoleEnter();
    }

    private void doAdminConsoleEnter() {
        final Authorization authorizationBundle = com.google.gwt.core.shared.GWT.create(Authorization.class);
        final MaskPanel maskPanel = new MaskPanel();

        if (this.display.getForm().validate()) {
            maskPanel.show();

            final UserServiceAsync userServiceAsync = GWT.create(UserService.class);
            userServiceAsync.retrieveUser(this.display.getUsernameItem().getValueAsString(),
                    this.display.getPasswordItem().getValueAsString(), new AsyncCallback<User>() {
                public void onFailure(Throwable caught) {
                    maskPanel.hide();
                    maskPanel.destroy();
                    // TODO: error screen should be implemented
                }

                public void onSuccess(User result) {
                    maskPanel.hide();
                    maskPanel.destroy();
                    final String errorMessage = result.getMessage();

                    if (errorMessage != null && !errorMessage.isEmpty()) {
                        processError(result);
                    } else {
                        presenter.eventBus().fireEvent(new LoginEvent());
                    }
                }
            });
        }
    }

    /**
     * Display error on the UI.
     * TODO: should be implemented using error enum
     *
     * @param result {@link User user} which contains <code>message</code> parameter with error type.
     */
    private void processError(User result) {
    }
}
